package com.panfeng.xcloud.common.security.web.support;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.panfeng.xcloud.common.core.component.SnowflakeIdWorker;
import com.panfeng.xcloud.common.core.constants.GlobalConstant;
import com.panfeng.xcloud.common.core.constants.RedisConstants;
import com.panfeng.xcloud.common.core.enums.ResponseStatusEnum;
import com.panfeng.xcloud.common.core.exceptions.BaseBizException;
import com.panfeng.xcloud.common.core.thread.ThreadLocalMap;
import com.panfeng.xcloud.common.core.utils.PublicUtil;
import com.panfeng.xcloud.common.core.utils.SpringContextUtil;
import com.panfeng.xcloud.common.core.utils.StringUtils;
import com.panfeng.xcloud.common.security.vo.SysSecurityUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;

import java.util.Map;
import java.util.UUID;

/**
 *
 * 业务base controller
 *
 * @author xiaobo
 * @version 1.0
 * @since 2018-12-28
 */
public class BaseController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	protected SysSecurityUser getCurrentUserByToken(String token){
		String accessTokenKey = RedisConstants.XDCLOUD_COMMON_ACCESS_TOKEN_PREFIX + token;
		StringRedisTemplate stringRedisTemplate = SpringContextUtil.getApplicationContext().getBean(StringRedisTemplate.class);
		if (null == stringRedisTemplate){
			logger.error(">>> 当前服务未注册缓存服务配置<<<");
			throw new BaseBizException(ResponseStatusEnum.CURRENT_NULL_REGISTER_CACHE_INFO_FAIL);
		}
		String userInfoDtoString = stringRedisTemplate.opsForValue().get(accessTokenKey);
		logger.info(">>> 获取当前用户信息.  userInfoDtoString={} <<<", userInfoDtoString);
		return JSON.parseObject(StringUtils.isEmpty(userInfoDtoString) ? "" : userInfoDtoString, SysSecurityUser.class);
	}

	protected String getCurrentUserNameByToken(String token) {
		Preconditions.checkArgument(!StringUtils.isEmpty(token), "传入的token不能为空");
		TokenStore tokenStore = SpringContextUtil.getApplicationContext().getBean(TokenStore.class);
		Preconditions.checkArgument(null != tokenStore, "spring上下文未初始化token存储bean");
		OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token);
		Preconditions.checkArgument(null != oAuth2AccessToken, "无法获取oauth token");
		//获取token中绑定的userId
		Map<String, Object> additionalInformation = oAuth2AccessToken.getAdditionalInformation();
		Preconditions.checkArgument(null != additionalInformation, "token附加信息为空");
		//手机号
		String loginName = (String) additionalInformation.get("loginName");
		logger.info(">>> 从token中获取当前用户的登录用户名：{} <<<",loginName);
		return loginName;
	}

	protected long generateId() {
		SnowflakeIdWorker snowflakeIdWorker = SpringContextUtil.getApplicationContext().getBean(SnowflakeIdWorker.class);
		if(null != snowflakeIdWorker){
			logger.info(">>> 雪花算法生成唯一标识<<<");
			return snowflakeIdWorker.nextId();
		}
		return UUID.randomUUID().timestamp();
	}

	protected String getCurrentUserId() {
		SysSecurityUser sysSecurityUser = (SysSecurityUser) ThreadLocalMap.get(GlobalConstant.Sys.TOKEN_AUTH_DTO);
		if (PublicUtil.isEmpty(sysSecurityUser)) {
			throw new BaseBizException(ResponseStatusEnum.GET_CURRENT_LOGIN_INFO_FAIL);
		}
		return sysSecurityUser.getUserId();
	}

	protected SysSecurityUser getCurrentSysSecurityUser() {
		SysSecurityUser sysSecurityUser = (SysSecurityUser) ThreadLocalMap.get(GlobalConstant.Sys.TOKEN_AUTH_DTO);
		if (PublicUtil.isEmpty(sysSecurityUser)) {
			throw new BaseBizException(ResponseStatusEnum.GET_CURRENT_LOGIN_INFO_FAIL);
		}
		return sysSecurityUser;
	}
}
